package dal

import "demo/dto/request"
import "demo/dto/response"
import "demo/model"
import "demo/utils/db_util"

type UserDao struct{}

var userDao *UserDao

func init() {
	userDao = &UserDao{}
}

func NewUserDao() *UserDao {
	return userDao
}

func (i *UserDao) SelectUserList(
	request *request.QueryUsersListRequest,
) ([]*response.UserResponse, error) {
	var result []*response.UserResponse
	db := db_util.GetDB().Model(&model.User{})

	// WHERE 条件构建
	if request != nil {
		if len(request.IDs) > 0 {
			db = db.Where("id IN ?", request.IDs)
		}
		if request.Name != nil {
			db = db.Where("name LIKE ?", "%"+*request.Name+"%")
		}
		if request.MinAge != nil {
			db = db.Where("age >= ?", *request.MinAge)
		}
		if request.MaxAge != nil {
			db = db.Where("age <= ?", *request.MaxAge)
		}
		if request.Status != nil {
			db = db.Where("status = ?", *request.Status)
		}

		//  时间范围查询
		if request.StartTime != nil {
			db = db.Where("created_at >= ?", *request.StartTime)
		}
		if request.EndTime != nil {
			db = db.Where("created_at <= ?", *request.EndTime)
		}
	}

	// 排序处理
	orderField := "id"
	orderDirection := "DESC"
	if request != nil {
		if request.OrderField != nil && *request.OrderField != "" {
			orderField = *request.OrderField
		}
		if request.Order != nil && *request.Order != "" {
			orderDirection = *request.Order
		}
	}
	db = db.Order(orderField + " " + orderDirection)

	// 分页处理
	page, pageSize := 1, 10
	if request != nil {
		if request.Page != nil && *request.Page > 0 {
			page = *request.Page
		}
		if request.PageSize != nil && *request.PageSize > 0 {
			pageSize = *request.PageSize
			if pageSize > 100 {
				pageSize = 100 // 限制最大页大小
			}
		}
	}
	offset := (page - 1) * pageSize
	db = db.Limit(pageSize).Offset(offset)

	// 执行查询
	err := db.Find(&result).Error
	if err != nil {
		return nil, err
	}

	return result, nil
}
